import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from './routes'
import store from '../store'

Vue.use(VueRouter)

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach(async (to, from, next) => {
  if (store.state.isToken) {
    console.log(to)
    const exist = router.getRoutes()
    console.log(exist)
    if (['/', '/Home'].includes(to.path)) {
      try {
        const route = [...store.state.admList]
        for (let i = 0; i < route.length; i++) {
          router.addRoute(route[i].name, route[i])
        }
        console.log(route)
        // router.addRoute(route)
        next({
          ...to,
          replace: true
        })
        // next()
      } catch (e) {
        console.log(e)
        return next()
      }
    }
  } else {
    next({ path: '/Login' })
  }
})

export default router
